#/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
import json
import requests
import time
import sys
from urllib import request
from fake_useragent import UserAgent


ua = UserAgent()

def getSong():
    print("--------酷狗音乐搜索下载----------")
    keyWord = input("请输入关键字(歌名,歌手)")
    search_url = "https://songsearch.kugou.com/song_search_v2?callback=jQuery1124001126207197192386_1556607293682&keyword={}&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1556607293686".format(keyWord)
    headers = {"UserAgent":ua.random}
    res = requests.get(search_url,headers = headers)
    start = re.search("jQuery\d+_\d+\(?", res.text)
    songJson = json.loads(res.text.strip().lstrip(start.group()).rstrip(")")) 
    song_list = songJson['data']['lists']
    for i in range(len(song_list)):
        song_name = (song_list[i]['FileName']).replace('<em>', '').replace('</em>', '')
        print(str(i+1)+"-----"+str(song_name))
    
        time.sleep(1)
        file_hash = song_list[i]['FileHash'] 
        song_name = song_list[i]['SongName'].replace('<em>', '').replace('</em>', '') 
        hash_url = "http://www.kugou.com/yy/index.php?r=play/getdata&hash={}".format(file_hash)
        hash_res = requests.get(hash_url,headers=headers)
        hash_js = hash_res.json()  # json格式
        play_url = hash_js['data']['play_url']
        if play_url == "": 
            print(play_url)
        else:    
            path = 'G:/py/爬虫/music/'+song_name+".mp3"
            downloader(play_url,path)

def downloader(url,path):
    start = time.time()
    size = 0
    response = requests.get(url,stream=True)
    chunk_size = 1024
    total_size = int(response.headers['content-length'])
    if response.status_code == 200:
        print("[文件大小]:%0.2f Mb"%(total_size/chunk_size/1024))
        with open(path,'wb') as fs:
            for data in response.iter_content(chunk_size = chunk_size):
                fs.write(data)
                size +=len(data)
                #print('\r'+'[下载进度]:%s%.2f%%' % ('>'*int(size*50/total_size),float(size / total_size * 100)))
    end = time.time()
    print('\n'+"歌曲下载完成！用时%.2f秒"%(end-start))
    
    
if __name__ =="__main__":
    
    getSong()